package com.wyk.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wyk.admin.common.biz.user.UserContext;
import com.wyk.admin.common.constant.ShortLinkGroupConstant;
import com.wyk.admin.common.convention.exception.ClientException;
import com.wyk.admin.common.convention.result.Result;
import com.wyk.admin.dao.entity.GroupDO;
import com.wyk.admin.dao.mapper.GroupMapper;
import com.wyk.admin.dto.req.GroupSortReqDTO;
import com.wyk.admin.dto.req.GroupUpdateReqDTO;
import com.wyk.admin.dto.resp.ShortLinkRespDTO;
import com.wyk.admin.remote.ShortLinkActualRemoteService;
import com.wyk.admin.remote.dto.resp.ShortLinkCountQuerRespDTO;
import com.wyk.admin.service.GroupService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static com.wyk.admin.common.constant.RedisCacheConstant.LOCK_GROUP_CREATE_KEY;

/**
 * 短连接分组接口实现层
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GroupServiceImpl extends ServiceImpl<GroupMapper,GroupDO> implements GroupService {

    private final RedissonClient redissonClient;

    private final GroupMapper groupMapper;

    @Value("${short-link.group.max-num}")
    private Integer groupMaxNum;

    private final ShortLinkActualRemoteService shortLinkSActuralRemoteService;

    /**
     * 新增短连接分组
     * @param Groupname
     */
    @Override
    public void saveGroup(String Groupname) {
        this.saveGroup(UserContext.getUsername(),Groupname);
    }
    @Override
    public void saveGroup(String username, String Groupname) {
        RLock lock = redissonClient.getLock(String.format(LOCK_GROUP_CREATE_KEY, username));
        lock.lock();
        try {
            LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                    .eq(GroupDO::getUsername, username)
                    .eq(GroupDO::getDelFlag, 0);
            List<GroupDO> groupDOList = baseMapper.selectList(queryWrapper);
            if (CollUtil.isNotEmpty(groupDOList) && groupDOList.size() == groupMaxNum) {
                throw new ClientException(String.format("已经超出最大分组数：%d", groupMaxNum));
            }
            String gid;
            while (true) {
                gid = RandomUtil.randomString(ShortLinkGroupConstant.GROUP_PARAM, 6);
                if (hasGids(username, Groupname)) {
                    break;
                }
            }
            GroupDO groupDO = GroupDO.builder()
                    .gid(gid)
                    .sortOrder(0)
                    .username(username)
                    .name(Groupname)
                    .build();
            baseMapper.insert(groupDO);
        }
        finally{
                lock.unlock();
            }

        }

    /**
     * 判断GID是否存在  不存在 true
     * @param gid
     * @return
     */
    private Boolean hasGid(String gid) {
        GroupDO hasGroupFalg = baseMapper.selectOne(Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getDelFlag,0)
                //TODO 设置用户名
                .eq(GroupDO::getUsername, UserContext.getUsername()));
        return hasGroupFalg == null;
    }
    //这个为了解决 注册用户时添加默认分组，UserContext为空的问题
    private Boolean hasGids(String username,String gid) {
        GroupDO hasGroupFalg = baseMapper.selectOne(Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getDelFlag,0)
                //TODO 设置用户名
                .eq(GroupDO::getUsername, Optional.ofNullable(username).orElse(UserContext.getUsername())));
        return hasGroupFalg == null;
    }


    /**
     * 修改短连接分组
     * @param groupUpdateReqDTO
     */
    @Override
    public void updateGroup(GroupUpdateReqDTO groupUpdateReqDTO) {
        if(hasGid(groupUpdateReqDTO.getGid())) {
           throw new ClientException("短连接不存在");
        }
        baseMapper.update(BeanUtil.toBean(groupUpdateReqDTO,GroupDO.class),
                Wrappers.lambdaUpdate(GroupDO.class)
                        .set(GroupDO::getName,groupUpdateReqDTO.getName())
                        .eq(GroupDO::getGid,groupUpdateReqDTO.getGid()));
    }

    /**
     * 删除短链接分组
     * @param gid
     */
    @Override
    public void deleteGroup(String gid) {
        if(hasGid(gid)){
            throw new ClientException("短连接不存在");
        }
        baseMapper.update(GroupDO.builder().gid(gid).build(),
                Wrappers.lambdaUpdate(GroupDO.class)
                        .eq(GroupDO::getUsername,UserContext.getUsername() )
                        .set(GroupDO::getDelFlag,1)
                        .eq(GroupDO::getGid,gid)
        );
    }

    /**
     * 查询用户短链接分组集合
     * @return
     */
    @Override
    public List<ShortLinkRespDTO> listGroup() {
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getDelFlag, 0)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .orderByDesc(GroupDO::getSortOrder, GroupDO::getUpdateTime);
        List<GroupDO> groupDOList = baseMapper.selectList(queryWrapper);
        Result<List<ShortLinkCountQuerRespDTO>> listResult = shortLinkSActuralRemoteService
                .listGroupShortLinkCount(groupDOList.stream().map(GroupDO::getGid).toList());
        List<ShortLinkRespDTO> shortLinkGroupRespDTOList = BeanUtil.copyToList(groupDOList, ShortLinkRespDTO.class);
        shortLinkGroupRespDTOList.forEach(each -> {
            Optional<ShortLinkCountQuerRespDTO> first = listResult.getData().stream()
                    .filter(item -> Objects.equals(item.getGid(), each.getGid()))
                    .findFirst();
            first.ifPresent(item -> each.setShortLinkCount(first.get().getShortLinkCount()));
        });
        return shortLinkGroupRespDTOList;
    }

    /**
     * 短连接分组排序
     * @param groupSortReqDTOList
     */
    @Override
    public void sortGroup(List<GroupSortReqDTO> groupSortReqDTOList) {
        groupSortReqDTOList.forEach(list -> {
            baseMapper.update(BeanUtil.toBean(list, GroupDO.class),
                    Wrappers.lambdaUpdate(GroupDO.class)
                            .eq(GroupDO::getGid,list.getGid())
                            .eq(GroupDO::getUsername,UserContext.getUsername())
                            .eq(GroupDO::getDelFlag,0)
            );
        });
    }
}
